package com.sr.servlet.User;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.sr.entity.User;
import com.sr.service.UserService;

/**
 * Servlet implementation class RegisterServlet
 */
@WebServlet("/register")
public class RegisterServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public RegisterServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.getWriter().append("Served at: ").append(request.getContextPath());
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html; charset=UTF-8");
		String username=request.getParameter("username");//根据表单中的name获取所填写的值
		String password=request.getParameter("password");	
		User user=new User(username,password);
		
		if(username==null || username.equals("")) {//判断当username为空时，
			System.out.println("用户名不能为空！");//控制台输出这玩意儿
			request.getRequestDispatcher("register.jsp").forward(request, response);//会返回注册页面继续。。。
		}else if(password==null || password.equals("")){
			System.out.println("密码不能为空！");
			request.getRequestDispatcher("register.jsp").forward(request, response);
		}else {//判断都不为空时，就调用service方法
				UserService us=new UserService();
				boolean result=us.addUser(user);//括号的user是实例化的
				if(result) {////注册成功后跳转的登录页面
					response.sendRedirect("login.jsp");
				}else {//不成功，停留在原页面
					System.out.println("注册失败，请重新输入账号或者密码！");
					request.getRequestDispatcher("register.jsp").forward(request, response);;
				}
		}
	}

}
